import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Button, message, Spin } from 'antd';
import SelectPath from '@/components/plugins/selectPath/index';
import { Design } from 'zent';
import configConf from './config/index';
import ConfigEditor from './config/ConfigEditor';
import whitespaceConf from '../../store/microPage/whitespace/index';
import lineConf from '../../store/microPage/line/index';
import richtextConf from '../../store/microPage/richtext/index';

import imageAdConf from '../../store/microPage/imagead/index';
import videoConf from '../../store/microPage/video/index';
import imagenavConf from '../../store/microPage/imagenav/index';
import storebanner from '../../store/microPage/storebanner/index';
import imageHotArea from '../../store/microPage/imageHotArea/index';
import baseInfoConf from './productBaseInfo/index';
import baseInfoEditor from './productBaseInfo/baseInfoEditor';
import detailConf from './productDetail/index';
import detailEditor from './productDetail/detailEditor';
import 'zent/css/index.css';
import 'zent/css/design-config.css';
import 'zent/css/design-whitespace.css';
import 'zent/css/design-line.css';
import 'zent/css/design-image-ad.css';

const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();

const namespace = 'micropage';
const groupedComponents = [
  Object.assign({}, configConf, {
    dragable: false, // 是否可以拖拽
    appendable: false, // 是否出现在底部的添加组件区域
     editable: false,// 是否可以编辑，UMP里面有些地方config是不能编辑的
    configurable: false,
    highlightWhenSelect: false,
  }),
  Design.group('基础组件'),
  richtextConf,
  imageAdConf,
  imagenavConf,
  Object.assign({ limit: 1 }, storebanner),
  videoConf,
  imageHotArea, // 热区
  Design.group('其他组件'),
  whitespaceConf,
  lineConf,
  Object.assign({}, baseInfoConf, {
    dragable: false, // 是否可以拖拽
    appendable: false, // 是否出现在底部的添加组件区域
    // editable: true,// 是否可以编辑，UMP里面有些地方config是不能编辑的
    configurable: false,
    //highlightWhenSelect: false,
  }),
  Object.assign({}, detailConf, {
    //dragable: false, // 是否可以拖拽
    appendable: false, // 是否出现在底部的添加组件区域
    // editable: true,// 是否可以编辑，UMP里面有些地方config是不能编辑的
    configurable: false,
    //highlightWhenSelect: false,
  }),
];
class Simple extends Component {
  state = {    
    value: [
      {
        type: configConf.type,
        ...ConfigEditor.getInitialValue(),
      },
      {
        type:baseInfoConf.type,
        ...baseInfoEditor.getInitialValue(),
      },
      {
        type:detailConf.type,
        ...detailEditor.getInitialValue(),
      }
    ],    
  };

  componentDidMount(){
    window.Isoption = true;
    const { value } = this.state;
    this.triggerDesignValidation();
    window.emitter=emitter;    
    this.itemChange = emitter.addListener('ItemChange',(data)=>{      
      if(data.type==='config'){
        value[1]={...data,type:"baseInfo","__zent-design-uuid__":value[1]["__zent-design-uuid__"]};
      }else{
        value[0]={...data,type:"config","__zent-design-uuid__":value[0]["__zent-design-uuid__"],};
      }
      let index=value.findIndex(item=>item.type==='productDetail'); 
      if(index>-1){
        value[index].specificationsType=data.specificationsType;
        value[index].detailType=  data.detailType;
      }       
      this.setState({
        value,
      })
    });//注册事件
  }

  componentWillMount() {
    window.Isoption = false;
    const { dispatch, match } = this.props;
    const { value } = this.state;
    let index=value.findIndex(item=>item.type==='productDetail');    
    const id = match.params.id ? match.params.id / 1 : 0;  
    value[0].specificationsType=  match.params.spectype > 0?match.params.spectype/1:1;
    value[0].detailType=  match.params.detailtype > 0?match.params.detailtype/1:1;
    value[1].specificationsType=  match.params.spectype> 0?match.params.spectype/1:1;
    value[1].detailType=  match.params.detailtype> 0?match.params.detailtype/1:1;
    if(index>-1){
      value[index].specificationsType=match.params.spectype > 0?match.params.spectype/1:1;
      value[index].detailType=  match.params.detailtype> 0?match.params.detailtype/1:1;
    }
    this.setState({
      value,
    });   
  }

  onChange = newValue => {
    this.setState({
      value: newValue,
    });
  };
  
  saveDesign = instance => {
    this.design = instance && instance.getDecoratedComponentInstance();
  };

  cancel = () => {
    router.replace(
        {
          pathname: `/${window.storeId}/goods/detailtemplates`,
        }                   
      );
  }

  submit = () => {
    this.triggerDesignValidation()
      .then(() => {
        const { dispatch } = this.props;
        const { value  } = this.state;
        const microinfo = value[0];
        //const datajson = JSON.stringify(value.slice(1));   
        const datajson = JSON.stringify(value);    
        const clonedata = { name:value[0].name, jsonData: datajson };
           
        dispatch({
          type: 'productDetailTemplate/CreateTemplate',
          payload:clonedata,
          callback: {
            success: res => {
              if (res.Code === 0) {
                message.success('提交成功');
                setTimeout(() => {
                  router.replace(
                    {
                      pathname: `/${window.storeId}/goods/detailtemplates`,
                    }                    
                  );
                });
              } else {
                message.error(res.Msg);
              }
            },
          },
        });
        this.design.markAsSaved();
      })
      .catch(validations => {
        console.log(validations);
      });
  };

  triggerDesignValidation() {
    return this.design.validate();
  }

  render() {
    const {  value } = this.state;
    const {  loading,  } = this.props;  
    return (
      <Fragment>
        <Spin spinning={ false}>
          <Card>
            <Design
              ref={this.saveDesign}
              cache={false}
              cacheId="zent-design-test"
              confirmUnsavedLeave={false}
              components={groupedComponents}
              value={value}
              onChange={this.onChange}
              //settings={settings}
              //onSettingsChange={this.onSettingsChange}
              scrollTopOffset={-270}
              globalConfig={window._global}                       
            />
          </Card>
        </Spin>
        <div className="xkd-bottom-actions">
          <Button onClick={this.cancel} className="xkd-mr16">取消</Button>
          <Button
            type="primary"
            onClick={this.submit}
            loading={loading}           
          >
            保存
          </Button>          
        </div>       
      </Fragment>
    );
  }
}
export default connect(({ productDetail,loading, storeinfo }) => ({ 
  loading: loading.effects['productDetailTemplate/CreateTemplate'], 
  storeinfo: storeinfo,
}))(Simple);
